<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import { ArrowLeft } from "@element-plus/icons-vue";
import router from "@/router";
import Document from "@/components/Document/index.vue";

defineOptions({
  name: "DocumentViewer"
});

const route = useRoute();
const documentUrl = ref<string>("");
const documentType = ref<"pdf" | "word" | "unknown">("unknown");

// 从路由参数或查询参数获取文档URL
const getDocumentUrl = () => {
  const url = (route.query.url as string) || (route.params.url as string);
  if (!url) {
    ElMessage.error("未提供文档URL");
    return;
  }
  documentUrl.value = url;
  detectDocumentType(url);
};

// 检测文档类型
const detectDocumentType = (url: string) => {
  const urlObj = new URL(url);
  const fullUrl = urlObj.origin + urlObj.pathname;

  const extension = fullUrl.split(".").pop();

  console.log("fullUrl", extension);
  if (extension === "pdf") {
    documentType.value = "pdf";
  } else if (["doc", "docx"].includes(extension || "")) {
    documentType.value = "word";
  } else {
    documentType.value = "unknown";
    ElMessage.warning("不支持的文档类型，仅支持 PDF 和 Word 文档");
  }
};

// 计算样式类
const containerClass = computed(() => {
  return {
    "document-viewer": true,
    "pdf-viewer": documentType.value === "pdf",
    "word-viewer": documentType.value === "word"
  };
});

const goBack = () => {
  router.back();
};

onMounted(() => {
  getDocumentUrl();
});
</script>

<template>
  <div :class="containerClass" class="common-page">
    <div class="document-header">
      <div class="flex items-center">
        <el-button :icon="ArrowLeft" text class="!p-2 mr-2" @click="goBack" />
        <span class="text-lg font-medium">文档详情</span>
      </div>
    </div>

    <Document v-if="documentUrl" :url="documentUrl" />
  </div>
</template>

<style lang="scss" scoped>
.document-viewer {
  height: 100vh;
  display: flex;
  flex-direction: column;

  .document-header {
    background: white;
    padding-bottom: 16px;
    border-bottom: 1px solid #e8e8e8;
    /* box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); */

    h3 {
      margin: 0 0 8px 0;
      color: #333;
      font-size: 18px;
      font-weight: 600;
    }

    .document-info {
      display: flex;
      align-items: center;
      gap: 16px;
      font-size: 14px;
      color: #666;

      .document-type {
        background: #e6f7ff;
        color: #1890ff;
        padding: 2px 8px;
        border-radius: 4px;
        font-size: 12px;
      }

      .document-url {
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .document-viewer {
    .document-header {
      padding: 12px 0;

      .document-info {
        flex-direction: column;
        align-items: flex-start;
        gap: 8px;
      }
    }
  }
}
</style>
